from fastapi import FastAPI, Request
from pydantic import BaseModel
from typing import List
import time
import multiprocessing
import pandas as pd
import json
import requests
import uvicorn
from Function import *
import sys


class Info(BaseModel):
    loan_type: str
    uuid_list: List[str]


app = FastAPI()


def run_model(uuid_list, loan_type, queue):
    dft = pd.DataFrame()
    print(uuid_list, file=sys.stderr)
    print(loan_type, file=sys.stderr)
    dft = classification_model(uuid_list, loan_type)
    print(dft.head())
    datas = {"project_type": loan_type, 'project_id': uuid_list}


    print('完成时间：' + time.strftime('%Y%m%d %H:%M:%S', time.localtime()))
    print('=' * 75 + '\n\n')
    queue.put(datas)
    return 0


def run_model_asyn(uuid_list, loan_type):
    dft = pd.DataFrame()
    print(uuid_list, file=sys.stderr)
    print(loan_type, file=sys.stderr)
    dft = classification_model(uuid_list, loan_type)

    datas = {"project_type": loan_type, 'project_id': uuid_list}

    print(dft.head())
    try:
        r = requests.post('http://10.49.157.42:8080/green/identify/callback', json=datas)
        print(r.content)
        print(r.status_code)
        print('回调接口成功', file=sys.stderr)
    except Exception as erm:
        print('回调接口失败 ' + erm, file=sys.stderr)

    print('完成时间：' + time.strftime('%Y%m%d %H:%M:%S', time.localtime()))
    print('=' * 75 + '\n\n')
    return 0

def run():
    api_pool = multiprocessing.Pool(1)
    queue = multiprocessing.Manager().Queue()

    @app.post('/green/identify/sync')
    def getInformation(info: Info):
        print('开始时间：' + time.strftime('%Y%m%d %H:%M:%S', time.localtime()))
        print('入参：',info.uuid_list,info.loan_type)
        api_pool.apply(run_model, (info.uuid_list, info.loan_type, queue,))
        result = queue.get()
        print('结束时间：' + time.strftime('%Y%m%d %H:%M:%S', time.localtime()))
        return result
    @app.post('/green/identify/call')
    def func(info:Info):
        print('开始时间：' + time.strftime('%Y%m%d %H:%M:%S', time.localtime()))
        print('入参:',info.uuid_list,info.loan_type)
        api_pool.apply(run_model_asyn, (info.uuid_list, info.loan_type,))
        print('结束时间：' + time.strftime('%Y%m%d %H:%M:%S', time.localtime()))
        return 'api work done'


if __name__ == '__main__':
    run()
    uvicorn.run(app=app,
                host="0.0.0.0",
                port=5100,
                workers=1)

# http://localhost:5100/green/identify/call